import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import router from '../router'
import { listStationApi, updateInfoApi } from '../api/station'

const stationSearchForm = reactive({})
const editStationForm = reactive({})
const editStationVisible = ref(false)
const stationListLoading = ref(true)
const stationList = reactive({
  arr: []
})
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)

async function getStationList() {
  stationListLoading.value = true
  const { data: res } = await listStationApi(stationSearchForm, currentPage.value, pageSize.value)
  stationList.arr = res.data.records
  total.value = res.data.total
  setTimeout(() => {
    stationListLoading.value = false
  }, 500)
}
async function editStation() {
  const { data: res } = await updateInfoApi(editStationForm)
  if (!res.success) {
    ElMessage.error({
      message: res.msg,
      dangerouslyUseHTMLString: true
    })
    return
  }
  getStationList()
  ElMessage.success(res.data)
  editStationVisible.value = false
}

function preEditStation(station) {
  Object.assign(editStationForm, station)
  editStationVisible.value = true
}
function jumpToPipeline(stationName) {
  router.push({
    path: '/pipelineManage',
    query: {
      stationName
    }
  })
}

export const useStation = () => {
  return {
    stationSearchForm,
    stationListLoading,
    stationList,
    editStationVisible,
    editStationForm,
    currentPage,
    pageSize,
    total,
    getStationList,
    preEditStation,
    editStation,
    jumpToPipeline
  }
}
